package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProjectFeignService;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SecKillSkuRedisTo;
import com.atguigu.gulimall.seckill.vo.SeckillSessionWithSkus;
import com.atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @title: SeckillServiceImpl
 * @Author syh
 * @Date: 2022/7/18 9:51
 * @Version 1.0
 */

@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProjectFeignService projectFeignService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";

    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//+商品随机码

    @Override
    public void uploadSeckillSkuLatest3Days() {
        // 1.扫描最近3天需要参与秒杀的活动
        R r = couponFeignService.getLates3DaySession();
        if (r.getCode() == 0) {
            List<SeckillSessionWithSkus> sessionData = r.getData(new TypeReference<List<SeckillSessionWithSkus>>() {
            });
            // 将所有商品信息缓存到redis
            // 1.缓存活动信息
            saveSessionInfos(sessionData);
            // 2.缓存活动关联的商品信息
            saveSessionSkuInfos(sessionData);

        }
    }

    public List<SecKillSkuRedisTo> blockHandler(BlockException e) {
        log.error("getCurrentSeckillSkusResource被限流了====>");
        return null;
    }

    /**
     * 获取当前时间可以参与的秒杀商品信息
     * <p>
     * blockHandler:  函数会在原方法被限流/降级/系统保护的时候调用，而 fallback 函数会针对所有类型的异常。
     *
     * @return
     */
    @SentinelResource(value = "getCurrentSeckillSkusResource", blockHandler = "blockHandler")
    @Override
    public List<SecKillSkuRedisTo> getCurrentSeckillSkus() {
        // 1.确定当前时间属于哪个秒杀场次
        long time = System.currentTimeMillis();
        Date date = new Date(time);

        try (Entry entry = SphU.entry("seckillSkus")) {
            Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
            if (keys != null && keys.size() > 0) {
                for (String key : keys) {
                    String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
                    String[] s = replace.split("_");
                    Long startTime = Long.parseLong(s[0]);
                    Long endTime = Long.parseLong(s[1]);
                    if (time >= startTime && time <= endTime) {
                        // 2.获取这个秒杀场次需要的所有商品信息
                        List<String> range = redisTemplate.opsForList().range(key, 0, -1);
                        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                        List<String> list = hashOps.multiGet(range);
                        if (list != null && list.size() > 0) {
                            List<SecKillSkuRedisTo> collect = list.stream().map(item -> {
                                SecKillSkuRedisTo to = JSON.parseObject(item.toString(), SecKillSkuRedisTo.class);
                                // 当前秒杀开始就需要随机码
//                            to.setRandomCode("");
                                return to;
                            }).collect(Collectors.toList());
                            return collect;
                        }
                        break;
                    }
                }
            }
        } catch (BlockException e) {
            log.error("<====资源被限流====>");
        }
        return null;
    }

    /**
     * 根据商品id获取当前秒杀数据
     *
     * @param skuId
     * @return
     */
    @Override
    public SecKillSkuRedisTo getSkuSeckillInfo(Long skuId) {

        // 1.找到所有参与秒杀的key信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
                    String json = hashOps.get(key);
                    SecKillSkuRedisTo skuRedisTo = JSON.parseObject(json, SecKillSkuRedisTo.class);

                    // 随机码,当前时间是不是秒杀时间
                    Long startTime = skuRedisTo.getStartTime();
                    long now = System.currentTimeMillis();
                    Long endTime = skuRedisTo.getEndTime();
                    if (now >= startTime && now <= endTime) {
                    } else {
                        skuRedisTo.setRandomCode("");
                    }
                    return skuRedisTo;
                }
            }
        }
        return null;
    }

    /**
     * 根据传来的参数进行秒杀操作,成功返回订单号
     *
     * @param killId
     * @param key
     * @param num
     * @return
     */
    @Override
    public String kill(String killId, String key, Integer num) {

        long timeMillis = System.currentTimeMillis();

        // 获取当前用户登录信息
        MemberResponseVo respVo = LoginUserInterceptor.loginUser.get();

        // 1.获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        String json = hashOps.get(killId);
        if (!StringUtils.isEmpty(json)) {
            SecKillSkuRedisTo redis = JSON.parseObject(json, SecKillSkuRedisTo.class);
            // 校验合法性
            // 校验时间是否符合要求,当前时间是否是指定的秒杀时间
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            long now = System.currentTimeMillis();

            // redis中过期时间
            long ttl = endTime - now;

            // 1.校验时间合法性
            if (now >= startTime && now <= endTime) {
                // 2.随机码校验和商品id是否正确
                String randomCode = redis.getRandomCode();
                String skuId = redis.getPromotionSessionId() + "_" + redis.getSkuId();
                if (randomCode.equals(key) && skuId.equals(killId)) {
                    // 3.验证购物数量是否合理
                    Integer seckillLimit = redis.getSeckillLimit();
                    if (num <= seckillLimit) {
                        // 4.验证当前人员是否已经抢购过:确保幂等性,只要用户秒杀成功,就去redis中占位
                        // 使用类似分布式锁,SETNX:不存在才保存,存在不保存
                        String redisKey = respVo.getId() + "_" + skuId;
                        // 一定要设置超时时间,确保redis空间充足
                        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(redisKey, String.valueOf(num), ttl, TimeUnit.MICROSECONDS);
                        if (ifAbsent) {
                            // 占位成功,说明该用户没有抢购过
                            // 占位成功之后,获取信号量,能获取到就是商品还有,还可以抢购;获取不到信号量就是没有商品可以抢购
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            // 尝试获取信号量
                            boolean tryAcquire = semaphore.tryAcquire(num);
                            if (tryAcquire) {
                                // 秒杀成功
                                String timeId = IdWorker.getTimeId();

                                // 保存到rabbitMQ队列中
                                // 发送消息
                                SeckillOrderTo orderTo = new SeckillOrderTo();
                                orderTo.setOrderSn(timeId);
                                orderTo.setMemberId(respVo.getId());
                                orderTo.setNum(num);
                                orderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                orderTo.setSkuId(redis.getSkuId());
                                orderTo.setSeckillPrice(redis.getSeckillPrice());
                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", orderTo);

                                long timeMillis1 = System.currentTimeMillis();
                                log.info("秒杀耗费时间====>" + String.valueOf(timeMillis1 - timeMillis) + "<====");

                                return timeId;
                            } else {
                                return null;
                            }

                        } else {
                            // 占位失败,说明该用户已经抢过该商品了
                            return null;
                        }
                    } else {
                        // 购买数量不合法
                        return null;
                    }
                } else {
                    // 随机码和商品id不合法
                    return null;
                }
            } else {
                // 时间不合法
                return null;
            }
        } else {
            // 没有获取到数据
            return null;
        }

    }

    /**
     * 保存活动信息到redis
     *
     * @param sessionData
     */
    private void saveSessionInfos(List<SeckillSessionWithSkus> sessionData) {
        sessionData.stream().forEach(session -> {
            Long startTime = session.getStartTime().getTime();
            Long endTime = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
            // 判断redis中是否存在这个key,如果有的话就不保存
            Boolean hasKey = redisTemplate.hasKey(key);
            if (!hasKey) {
                List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_" + String.valueOf(item.getSkuId())).collect(Collectors.toList());
                // 缓存活动信息
                redisTemplate.opsForList().leftPushAll(key, collect);
            }
        });
    }

    /**
     * 保存活动关联的商品信息
     *
     * @param sessionData
     */
    private void saveSessionSkuInfos(List<SeckillSessionWithSkus> sessionData) {
        sessionData.stream().forEach(session -> {
            // 准备hash操作
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(seckillSkuVo -> {
                Boolean aBoolean = ops.hasKey(String.valueOf(seckillSkuVo.getPromotionSessionId()) + "_" + String.valueOf(seckillSkuVo.getSkuId()));

                // 4.设置商品随机码
                String token = UUID.randomUUID().toString().replace("-", "");

                if (!aBoolean) {
                    // 缓存商品
                    SecKillSkuRedisTo redisTo = new SecKillSkuRedisTo();

                    // 1.sku基本数据
                    R r = projectFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    if (r.getCode() == 0) {
                        SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        redisTo.setSkuInfo(skuInfo);
                    }

                    // 2.sku秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo, redisTo);

                    // 3.设置当前商品秒杀时间信息
                    redisTo.setStartTime(session.getStartTime().getTime());
                    redisTo.setEndTime(session.getEndTime().getTime());

                    redisTo.setRandomCode(token);

                    String jsonString = JSON.toJSONString(redisTo);
                    ops.put(String.valueOf(seckillSkuVo.getPromotionSessionId()) + "_" + String.valueOf(seckillSkuVo.getSkuId()), jsonString);

                    // 如果当前这个场次的库存信息已经上架就不需要再上架了

                    // 5.引入分布式信号量,使用库存作为分布式的信号量
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    // 商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                }
            });
        });
    }
}
